package com.tronsis.distribution.activity.me;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.agent.AgentExitActivity;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.WindowUtil;
import com.tronsis.library.widget.CircleImageView;
import com.tronsis.library.widget.ConfirmDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人信息
 */
public class ProfileActivity extends ToolBarBaseActivity {

    @BindView(R.id.ll_nick_name)
    LinearLayout mLlNickName;
    @BindView(R.id.ll_phone)
    LinearLayout mLlPhone;
    @BindView(R.id.ll_id)
    LinearLayout mLlId;
    @BindView(R.id.ll_wechat)
    LinearLayout mLlWechat;
    @BindView(R.id.ll_wechat_card)
    LinearLayout mLlWechatCard;
    @BindView(R.id.ll_agent_role)
    LinearLayout mLlAgentRole;
    @BindView(R.id.ll_agent_level)
    LinearLayout mLlAgentLevel;
    @BindView(R.id.ll_province)
    LinearLayout mLlProvince;
    @BindView(R.id.ll_market_contribution)
    LinearLayout mLlMarketContribution;
    @BindView(R.id.ll_sales)
    LinearLayout mLlSales;
    @BindView(R.id.ll_margin)
    LinearLayout mLlMargin;
    @BindView(R.id.ll_payee_account)
    LinearLayout mLlAccountNumber;
    @BindView(R.id.ll_exit_agent)
    LinearLayout mLlExitAgent;
    @BindView(R.id.btn_logout)
    Button mBtnLogout;
    @BindView(R.id.iv_cover)
    CircleImageView mIvCover;
    @BindView(R.id.ll_avatar)
    LinearLayout mLlAvatar;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_id_num)
    TextView mTvIdNum;
    @BindView(R.id.tv_wechat)
    TextView mTvWechat;
    @BindView(R.id.tv_wechat_card)
    TextView mTvWechatCard;
    @BindView(R.id.tv_role)
    TextView mTvRole;
    @BindView(R.id.tv_level)
    TextView mTvLevel;
    @BindView(R.id.tv_area)
    TextView mTvArea;
    @BindView(R.id.tv_contribute)
    TextView mTvContribute;
    @BindView(R.id.tv_sales)
    TextView mTvSales;
    @BindView(R.id.tv_margin)
    TextView mTvMargin;

    private static final int REQ_CAMERA = 124;
    private static final int REQUEST_CAMERA = 125;
    private static final int REQUEST_ALBUM = 126;
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.personal_info));
        EventBus.getDefault().register(this);
        setUserView();
        httpGetUserInfo();
    }

    private void setUserView() {
        UserBean userBean = UserBizFactory.createBiz().getLoginUser(mContext);
        if (userBean != null) {
            ImageLoader.displayAvatar(mContext, Url.FILE_DOWNLOAD + userBean.getAvatarFid(), mIvCover);
            mTvName.setText(TextUtils.isEmpty(userBean.getName()) ? "" : userBean.getName());
            mTvPhone.setText(userBean.getPhone());
            mTvIdNum.setText(userBean.getIdCardNo());
            mTvWechat.setText(userBean.getWechatId());
//            mTvWechatCard.setText(userBean.getWechatId());
            mTvRole.setText(StateUtil.getRoleString(mContext, userBean.getRole()));
            mTvLevel.setText(StateUtil.getLevelText(userBean.getLevel(),userBean.isUnited()));
            String region = CommonUtil.getRegionString(userBean.getRegion());
            mTvArea.setText(region);
            mTvContribute.setText(String.valueOf(userBean.getContribute()));
            mTvSales.setText(userBean.getSales() == 0 ? "0" : getString(R.string.format_price, userBean.getSales()));
            mTvMargin.setText(userBean.getDeposit() == 0 ? "0" : getString(R.string.format_price, userBean.getDeposit()));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (imageItems != null && imageItems.size() > 0) {
                ImageLoader.display(mContext, imageItems.get(0).path, mIvCover);
                httpUploadAvatar(new File(imageItems.get(0).path));
            }
        }

        if ((requestCode == 100 || requestCode == 200) && resultCode == RESULT_OK) {
            setUserView();
        }
    }

    @OnClick(R.id.ll_avatar)
    void avatarClick() {
        showPopupWindow();
    }

    @OnClick(R.id.ll_exit_agent)
    void exitAgentClick() {
        startActivity(new Intent(mContext, AgentExitActivity.class));
    }

    @OnClick(R.id.ll_payee_account)
    void accountNumber() {
        startActivity(new Intent(mContext, PayeeAccountActivity.class));
    }

    @OnClick(R.id.ll_nick_name)
    void nickNameClick() {
        Intent intent = new Intent(mContext, NickNameActivity.class);
        intent.setType("nickname");
        startActivityForResult(intent, 100);
    }

    @OnClick(R.id.ll_id)
    void idNumClick() {
        Intent intent = new Intent(mContext, NickNameActivity.class);
        intent.setType("id");
        startActivityForResult(intent, 200);
    }

    @OnClick(R.id.ll_wechat)
    void wechatNumClick() {
        Intent intent = new Intent(mContext, NickNameActivity.class);
        intent.setType("wechat");
        startActivityForResult(intent, 200);
    }

    @OnClick(R.id.ll_wechat_card)
    void wechatCardClick() {
        Intent intent = new Intent(mContext, WechatCardActivity.class);
        startActivityForResult(intent, 200);
    }

    @OnClick(R.id.ll_province)
    void regionClick() {
        Intent intent = new Intent(mContext, RegionActivity.class);
        startActivity(intent);
//        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
//            @Override
//            public void onLeftButtonClick(View view) {
//            }
//
//            @Override
//            public void onRightButtonClick(View view) {
//                showRegionPop();
//            }
//        }).showDialog("归属地修改将影响您的贡献值\n" +
//                " 是否确认修改？", "否", "是");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.MY_REGION:
                String region = CommonUtil.getRegionString((String) message.getParams());
                mTvArea.setText(region);
                break;
            default:
                break;
        }
    }
    @OnClick(R.id.btn_logout)
    void logoutClick() {
        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {

            }

            @Override
            public void onRightButtonClick(View view) {
                UserBizFactory.createBiz().logout(ProfileActivity.this);
            }
        }).showDialog("确定退出？", "取消", "确定");
    }

    private void showPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_album_camera, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mPopupWindow == null) {

            ImagePicker imagePicker = ImagePicker.getInstance();
            imagePicker.setImageLoader(new GlideImageLoader());
            imagePicker.setCrop(true);
            imagePicker.setMultiMode(false);
            imagePicker.setShowCamera(true);
            imagePicker.setFocusHeight(DisplayUtil.getInstance(mContext).dip2px(240));
            imagePicker.setFocusWidth(DisplayUtil.getInstance(mContext).dip2px(240));

            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            /* mPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mPopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(ProfileActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                }
            });
            view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, REQUEST_CAMERA);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.CAMERA);
                }
            });
            view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);

                            startActivityForResult(intent, REQUEST_ALBUM);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
                }
            });
        }
        WindowUtil.setPopWindowBackgroundAlpha(ProfileActivity.this, 0.7f);
        mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void httpUploadAvatar(final File file) {
        try {
            FileBizFactory.createBiz().upload(this, file, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    UploadFileBean fileBean = (UploadFileBean) data;
                    LogUtil.e("file", fileBean.getId());
                    httpUpdateUserInfo(fileBean.getId());
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void httpUpdateUserInfo(final String fileId) {
        try {
            final UserBean userBean = UserBizFactory.createBiz().getLoginUser(mContext);
            UserBizFactory.createBiz().updateInfo(this, userBean.isAppNotice(), fileId, null, null, null, null, null, null, null, null, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ImageLoader.display(mContext, Url.FILE_DOWNLOAD + fileId, mIvCover);
                    userBean.setAvatarFid(fileId);
                    DBUtil.getInstance(mContext).update(userBean);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpUpdateUserRegion(String region) {
        if (region.length() < 6) {
            StringBuilder regionBuilder = new StringBuilder(region);
            for (int i = 0; i < (6 - region.length()); i++) {
                regionBuilder.append("0");
            }
            region = regionBuilder.toString();
        }
        try {
            final UserBean userBean = UserBizFactory.createBiz().getLoginUser(mContext);
            final String finalRegion = region;
            UserBizFactory.createBiz().updateInfo(this, userBean.isAppNotice(), null, null, null, null, null, null, region, null, null, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    userBean.setRegion(finalRegion);
                    DBUtil.getInstance(mContext).update(userBean);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpGetUserInfo() {
        try {
            UserBizFactory.createBiz().getUserInfo(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    setUserView();
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
